<?php

namespace App\Libraries\Enigma;

class EnigmaHelper
{
    // 加密函数
    static function encrypt($data): string
    {
        if (is_array($data)) {
            $data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        $key = base64_decode(config('services.encrypt.key'));
        $iv = hex2bin(config('services.encrypt.iv'));

        $payload = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);

        return base64_encode($payload);
    }

    // 解密函数
    static function decrypt($data): string
    {
        $key = base64_decode(config('services.encrypt.key'));
        $iv = hex2bin(config('services.encrypt.iv'));

        $data = base64_decode($data);

        return openssl_decrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
    }
}
